import time
from django.shortcuts import render, redirect
from django.http import JsonResponse

from web.models import Project, ProjectUser
from web.forms.project import addProjectForm
from utils.tencent.cos import CosTencent
from projectmanager import settings


def project_list(request):
    """项目列表"""
    # GET 请求获取项目列表
    if request.method == 'GET':
        project_dict = {
            'create': [],
            'join': [],
            'star':[]
        }
        create_list = Project.objects.filter(creator=request.login_user.user).all()
        partner_list = ProjectUser.objects.filter(user=request.login_user.user).all()
        for item in create_list:
            if item.star:
                project_dict['star'].append({'value': item, 'type': 'create'})
            else:
                project_dict['create'].append(item)
        for item in partner_list:
            if item.star:
                project_dict['star'].append({'value': item, 'type': 'join'})
            else:
                project_dict['join'].append(item)

        add_project_form = addProjectForm(request)
        return render(request,
                      'web/project_list.html',
                      {'add_project_form': add_project_form,
                       'project_dict':project_dict,
                       })
    # POST 请求创建项目 & 并为项目创建一个桶 & 为创建的桶开启跨域
    form = addProjectForm(request, data=request.POST)
    if form.is_valid():
        # 1 创建项目时候为这个项目创建一个存储桶
        cos = CosTencent()
        # 2 存储桶的命名格式是手机号-时间戳-cos APPID
        mobile_phone = request.login_user.user.mobile_phone
        name = form.cleaned_data.get('name')
        bucket_name = f'{mobile_phone}-{str(int(time.time()))}-{settings.TENCENT_COS_APP_ID}'
        cos.create_bucket(bucket_name=bucket_name)
        form.instance.bucket_name = bucket_name
        form.instance.bucket_region = settings.TENCENT_COS_REGION
        form.instance.creator = request.login_user.user
        form.save()
        return JsonResponse({'status': True})
    else:
        return JsonResponse({'status':False, 'error': form.errors})


def add_star(request, project_type, project_id):
    """增加星标"""
    if project_type == 'create':
        Project.objects.filter(id=project_id).update(star=True)
        return redirect('project_list')
    if project_type == 'join':
        ProjectUser.objects.filter(id=project_id).update(star=True)
        return redirect('project_list')
    return JsonResponse({'status': 'False'})


def remove_star(request,project_type, project_id):
    """移除星标"""
    if project_type == 'create':
        Project.objects.filter(id=project_id).update(star=False)
        return redirect('project_list')
    if project_type == 'join':
        ProjectUser.objects.filter(id=project_id).update(star=False)
        return redirect('project_list')
    return JsonResponse({'status': 'False'})